<template>
    <div class="register-container">
        <van-nav-bar title="注册账号" left-text="返回" left-arrow @click-left="onClickLeft" fixed >
            <template #left>
                <van-icon name="arrow-left" size="24" color="gray" />
            </template>
        </van-nav-bar>
        <div class="register-form">
            <van-form @submit="onSubmit">
                <van-cell-group inset class="register-panel">
                    <h1>创建账号</h1>
                    <van-cell title="手机号码" class="label-cell" :border="false" />
                    <van-field v-model="phone" left-icon="phone" name="phone" placeholder="请输入手机号码"
                        :rules="[{ required: true, message: '请填写手机号码' }]" />
                    <van-cell title="用户名" class="label-cell" :border="false" />
                    <van-field v-model="username" left-icon="user" name="username" placeholder="请输入用户名"
                        :rules="[{ required: true, message: '请填写用户名' }]" />
                    <van-cell title="真实姓名" class="label-cell" :border="false" />
                    <van-field v-model="realname" left-icon="user" name="realname" placeholder="请输入真实姓名"
                        :rules="[{ required: true, message: '请填写真实姓名' }]" />
                    
                    <!-- 添加身份选择 -->
                    <van-cell title="注册身份" class="label-cell" :border="false" />
                    <div class="identity-selection">
                        <van-radio-group v-model="userType" direction="horizontal">
                            <van-radio name="0" icon-size="18px" checked-color="#4f46e5">零工</van-radio>
                            <van-radio name="1" icon-size="18px" checked-color="#4f46e5">雇主</van-radio>
                        </van-radio-group>
                    </div>
                    
                    <van-cell title="验证码" class="label-cell" :border="false" />
                    <van-field v-model="smsCode" center clearable placeholder="请输入验证码"
                        :rules="[{ required: true, message: '请填写验证码' }]">
                        <template #button>
                            <van-button style="border-radius: 10px;" color="#4f46e5" size="small" type="primary"
                                @click="onSendSms">
                                发送验证码
                            </van-button>
                        </template>
                    </van-field>
                    <van-cell title="设置密码" class="label-cell" :border="false" />
                    <van-field v-model="password" type="password" left-icon="lock" name="password" placeholder="请设置登录密码"
                        :rules="[{ required: true, message: '请设置登录密码' }]" />
                    <van-cell title="确认密码" class="label-cell" :border="false" />
                    <van-field v-model="confirmPassword" type="password" left-icon="lock" name="confirmPassword"
                        placeholder="请再次输入密码" :rules="[
                            { required: true, message: '请再次输入密码' },
                            { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
                        ]" />
                    <div class="agreement">
                        <van-checkbox v-model="agreeTerms"
                            :rules="[{ validator: validateAgreement, message: '请阅读并同意服务条款和隐私政策' }]">
                            我已阅读并同意
                            <span class="link" @click="showTerms">《服务条款》</span>
                            和
                            <span class="link" @click="showPrivacy">《隐私政策》</span>
                        </van-checkbox>
                    </div>
                    <div style="margin-top: 30px;">
                        <van-button style="border-radius: 10px;" color="#4f46e5" block type="primary"
                            native-type="submit">
                            注册
                        </van-button>
                    </div>
                </van-cell-group>
            </van-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import network from '@/network'

const router = useRouter()
const phone = ref('')
const username = ref('')
const realname = ref('')
const smsCode = ref('')
const password = ref('')
const confirmPassword = ref('')
const agreeTerms = ref(false)
// 添加用户类型选择，默认为零工(0)
const userType = ref('0')

const onClickLeft = () => {
    router.back()
}

// 在onSubmit函数中修改注册成功后的处理逻辑
const onSubmit = (values: any) => {
    if (!agreeTerms.value) {
        showToast('请阅读并同意服务条款和隐私政策');
        return;
    }

    if (!smsCode.value) {
        showToast('请输入验证码');
        return;
    }

    // 构建注册用户对象
    const user = {
        phone: phone.value,
        username: username.value,
        realname: realname.value,
        password: password.value,
        userType: parseInt(userType.value),  // 将字符串转换为数字
        status: 1,
        isDeleted: 0
    };

    network.register(user)
        .then((res) => {
            if (res.data.code === 100) {
                showToast({
                    message: '注册成功',
                    type: 'success'
                });
                
                // 注册成功后，先自动登录
                return network.login({ username: username.value, password: password.value });
            } else {
                showToast({
                    message: res.data.message || '注册失败',
                    type: 'fail'
                });
                return Promise.reject('注册失败');
            }
        })
        .then((loginRes) => {
            // 登录成功后，保存用户信息
            if (loginRes && loginRes.data) {
                localStorage['user_info'] = JSON.stringify(loginRes.data.data || loginRes.data);
                
                // 然后上传默认头像
                return uploadDefaultAvatar();
            }
            return Promise.reject('登录失败');
        })
        .then(() => {
            // 头像上传成功后跳转到首页
            router.push('/');
        })
        .catch((err) => {
            console.error('处理过程中出错:', err);
            // 即使出错，也跳转到登录页
            router.push('/Mlogin');
        });
}

// 添加上传默认头像的函数
const uploadDefaultAvatar = async () => {
    try {
        // 创建一个fetch请求获取默认头像文件
        const response = await fetch('/image/OIP-C.jpg');
        const blob = await response.blob();
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', blob, 'default-avatar.jpg');
        
        // 调用上传头像API
        const result = await network.uploadAvatar(formData);
        return result;
    } catch (error) {
        // 即使头像上传失败，也不影响注册流程
        return Promise.resolve();
    }
};

const onSendSms = () => {
    if (!phone.value) {
        showToast('请输入手机号码')
        return
    }

    // 生成6位随机验证码
    const randomCode = Math.floor(100000 + Math.random() * 900000).toString()
    smsCode.value = randomCode

    // 显示生成的验证码
    showToast({
        message: `验证码已发送: ${randomCode}`,
        position: 'bottom',
        duration: 3000
    })
}

const validateConfirmPassword = (val: string) => {
    return val === password.value
}

const validateAgreement = (val: boolean) => {
    return val === true
}

const showTerms = () => {
    // TODO: 显示服务条款
    showToast('服务条款')
}

const showPrivacy = () => {
    // TODO: 显示隐私政策
    showToast('隐私政策')
}
</script>

<style scoped>
.register-container {
    min-height: 100vh;
    background-color: #f7f8fa;
}

.register-form {
    padding: 20px;
}

.register-panel {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-radius: 20px;
    padding: 30px;
    background: #fff;
    margin-bottom: 46px !important;
    margin-top: 46px !important;
}

h1 {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
    font-size: 24px;
}

.label-cell {
    padding: 0px;
    padding-top: 16px;
    text-align: left;
    font-size: 16px;
}

/* 添加身份选择样式 */
.identity-selection {
    padding: 10px 15px;
    margin-bottom: 10px;
}

:deep(.van-radio) {
    margin-right: 20px;
}

:deep(.van-field) {
    border: 1px solid #dcdee0;
    border-radius: 20px;
    padding-left: 10px;
}

:deep(.van-field__control) {
    padding-left: 10px;
}

:deep(.van-cell::after) {
    display: none;
}

:deep(.van-cell-group--inset) {
    margin: 0;
}

:deep(.van-field__error-message) {
    position: static;
    margin-top: 4px;
    padding-left: 10px;
    color: #ee0a24;
    font-size: 12px;
}

:deep(.van-field--error) {
    border-color: #ee0a24;
}

.agreement {
    margin: 20px 0;
    padding: 0 10px;
}

:deep(.van-checkbox__label) {
    color: #666;
    font-size: 14px;
}

.link {
    color: #4f46e5;
    cursor: pointer;
}
</style>